package com.nefu.store.user.controller;


import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.nefu.store.common.result.HttpResult;
import com.nefu.store.domain.entity.User;
import com.nefu.store.user.mapper.UserMapper;
import com.nefu.store.user.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Tag(name = "测试用户模块api")
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private final static String SALT = "longsir";

    @Operation(summary = "查询所有用户")
    @GetMapping("/findAllUser")
    public HttpResult findAllUser(HttpServletRequest request) {
        String token = request.getHeader("login-token");
        Boolean haskey = stringRedisTemplate.hasKey(token);
        if(haskey){
            return HttpResult.success(userService.findAllUser());
        }
        else{
            return HttpResult.failed("用户未登录异常！");
        }
//
//        List<User>  users = userService.findAllUser();
//        List<UserVo> list = new ArrayList<UserVo>();
//
//        users.forEach(user -> {
//            UserVo uv = new UserVo(user);
//            list.add(uv);
//        });
//        return HttpResult.success(list);
    }

    @SneakyThrows
    @Operation(summary = "用户登录认证")
    @GetMapping("/login")
    public HttpResult<String> login(String username, String password) {

        User user = userService.login(username, password);
        String token = JWT.create()
                .withClaim("username", username) // 数据
                .withExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 30)) // 设置过期时间(默认过期时间30分钟)
                .sign(Algorithm.HMAC256(SALT));// 数字签名

        ObjectMapper mapper = new ObjectMapper();
        String userStr = mapper.writeValueAsString(user);

        stringRedisTemplate.opsForValue().set(token,userStr,30, TimeUnit.MINUTES);

        return HttpResult.success(token);

    }


    @SneakyThrows
    @Operation(summary = "用户注册api")
    @PostMapping("/addUser")
    public HttpResult addUser(@RequestBody User user) {
        userService.register(user);
        return HttpResult.success(user.getId());
    }
}
